from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView

from oauth.exceptions import QQAPIException
from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from rest_framework.permissions import IsAuthenticated


class OAuthURLView(APIView):
    def get(self, request):
        state = request.query_params.get('state')
        if not state:
            state = '/'  # 如果前端未指明，我们设置用户QQ登录成功后，跳转到主页
        oauth = OAuthQQ(state=state)
        login_url = oauth.get_qq_login_url()
        return Response({'login_url': login_url})


from .serializer import OAuthQQUserSerializer


class QQAuthUsersView(GenericAPIView):
    serializer_class = OAuthQQUserSerializer

    def get(self, request):

        code = request.query_params.get('code')
        if not code:
            return Response({"message": "缺少code"}, status=status.HTTP_400_BAD_REQUEST)
    
        # 凭借code向QQ服务器发起请求，获取access_token
        oauth_qq = OAuthQQ()
        try:
            access_token = oauth_qq.get_access_token(code)
        
            # 凭借 access_token向QQ服务器发送请求，获取openid
            openid = oauth_qq.get_openid(access_token)
        except QQAPIException:
            return Response({'message': '获取QQ用户数据异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
    
        # 根据openid查询此用户是否之前在美多中绑定或用户
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果未绑定，手动创建接下来绑定身份使用的access_token, 并返回
            access_token = OAuthQQUser.generate_save_user_token(openid)
            return Response({'access_token': access_token})
        else:
            # 如果已经绑定，直接生成登录凭证 JWT token，并返回
            # 手动为用户生成JWT token
            user = oauth_user.user
        
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })
    
    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        
        return Response({
            'token': token,
            'username': user.username,
            'user_id': user.id
        })
    

# Create your views here.
